package com.qf.myshop.dao.impl;

import com.qf.myshop.dao.ProductDAO;
import com.qf.myshop.entity.Product;
import com.qf.myshop.utils.DruidUtils;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProductDAOImpl implements ProductDAO {
        private QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        private  Map<String,String> map = new HashMap<>();
    {
        map.put("p_id","pid");
        map.put("t_id","tid");
        map.put("p_name","pname");
        map.put("p_time","ptime");
        map.put("p_image","pimage");
        map.put("p_state","pstate");
        map.put("p_info","pinfo");
        map.put("p_price","pprice");
    }

    //查询所有
    @Override
    public List<Product> list(int tid) {
        String sql = "select * from product where t_id =?";
        try {
            List<Product> query = queryRunner.query(sql, new BeanListHandler<>(Product.class, new BasicRowProcessor(new BeanProcessor(map))),tid);
             return query;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
    //分页查询
    @Override
    public List<Product> list(int tid, int begin, int finish) {
        String sql = "SELECT * FROM product WHERE t_id = ? limit ?,?";
        try {
            List<Product> query = queryRunner.query(sql,
                                 new BeanListHandler<>(Product.class,
                            new BasicRowProcessor(new BeanProcessor(map)))
                            ,tid,((begin - 1) * finish),finish);
            return query;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;


    }

    //查询个数
    @Override
    public Long count(int tid) {
        String sql="select count(*) from product WHERE t_id = ?";
        try {
            Long result = queryRunner.query(sql, new ScalarHandler<>(),tid);
            return result;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
    //查询一个
    @Override
    public Product listone(int pid) {
        String sql="select * from product WHERE p_id = ?";
        try {
            Product result = queryRunner.query(sql, new ScalarHandler<>(),pid);
            System.out.println(result+"12111111111111111111111");
            return result;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

}
